<template>
  <el-container class="height100 ">
    <el-container direction="vertical" 
    v-loading="loading"
    :element-loading-text="$t('msg_syn')"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.5)" class="weixinCon bigBgColor">
      <div  class="width100 height100 overflowy">
        <div class="partContent">
          <div class="part padding0">
          <header_item  :headerArr="headerArr"  @onBtnClick="onBtnClick"/>
           <div class="partForm">
        <el-form :inline="true" class="demo-form-inline wexinForm rowItem">
        <el-form-item :label="$t('activate_weChat')" >
          <el-radio-group v-model="wechatConfigs.weixinProxyType" @change="changeShow">
            <el-radio label="none">{{$t('no_wechat_service')}}</el-radio>
            <!-- <el-radio label="cloud">云端智能托管模式</el-radio> -->
            <el-radio label="EnterpriseWeChat">{{$t('enterprise_wechat')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        </el-form>

        <div v-show="wechatConfigs.weixinProxyType=='cloud'">
          <a
            class="d-inline-block obpm-btn obpm-btn-primary el-button el-button--primary el-button--small is-plain"
            :href="'http://yun.weioa365.com/weixin/main?siteId=Z1IED1IEA1M&amp;domainId='+$route.query.domainid"
            target="_blank"
            style="text-decoration:none"
          >{{$t('startup')}}</a>
        </div>

        <el-form
          :model="wechatConfigs"
          ref="wechatConfigs"
          label-position="top"
          label-width="180px"
          size="small"
          :rules="rules"
          v-show="wechatConfigs.weixinProxyType=='EnterpriseWeChat'"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item :label="$t('weixincorpID')" prop="weixinCorpID">
                <el-input v-model="wechatConfigs.weixinCorpID"  :placeholder="$t('placeholder_enter_content')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('weixinCorpSecret')" prop="weixinCorpSecret"    >
                <el-input v-model="wechatConfigs.weixinCorpSecret" :placeholder="$t('placeholder_enter_content')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('serverHost')" prop="serverHost" class="verifyItem">
                <el-input v-model="wechatConfigs.serverHost" placeholder="http://www.xxx.com/obpm">
                  <template slot="append">
                    <el-button plain type="primary" @click="onVerifyBtnClick">{{$t('verify_link')}}</el-button>
                 </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="8">
              <el-form-item :label="$t('weixinQrCodeAgentId')" prop="weixinQrCodeAgentId"    >
                <el-input v-model="wechatConfigs.weixinQrCodeAgentId" :placeholder="$t('placeholder_enter_content')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('weixinQrCodeSecret')" prop="weixinQrCodeSecret"    >
                <el-input v-model="wechatConfigs.weixinQrCodeSecret" :placeholder="$t('placeholder_enter_content')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('weixinQrCodeCallbackUrl')" prop="weixinQrCodeCallbackUrl"    > 
                <el-input v-model="wechatConfigs.weixinQrCodeCallbackUrl" placeholder="http://www.xxx.com/signon/runtime/login/wxqrcodelogin"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
           </div>
      </div>
        <div class="part"  v-show="wechatConfigs.weixinProxyType=='EnterpriseWeChat'">
        <p class="smallHeader">{{$t('enabled_software')}}</p>
        <el-table
          :data="wechatConfigs.apps"
          class="el-table-w marginT24"
          header-cell-class-name="tableHeaderbg"
          size="small"
        >
          <el-table-column prop="name" :label="$t('software_name')" width="180"></el-table-column>
          <el-table-column prop="description" :label="$t('description')" width="180"></el-table-column>
          <el-table-column :label="$t('weixinAgentId')">
            
            <template slot-scope="scope">
                <i class="iconfont icon-Frame" @click="editAgentId(scope.row)"></i>
                <span>{{scope.row.weixinAgentId}}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('weixinSecret')">
            <template slot-scope="scope">
              <i class="iconfont icon-Frame" @click="editSecret(scope.row)"></i>
              <span>{{scope.row.weixinSecret}}</span>
              <!-- <el-input type="text" v-model="scope.row.weixinSecret"  @blur="onSaveWeixinSecret(scope.row)" /> -->
            </template>
          </el-table-column>
          <el-table-column :label="$t('weChatURL')">
            <template slot-scope="scope">
              <el-button @click="genWeChatURL(scope.row)" type="primary" plain size="small" >{{$t('jumplink')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
     </div>
    </div>
    </el-container>
    <weixin_result :visible.sync="weixinResultVisible" :weixinResult="weixinResult" type="weixin" @exit="onBack"/>
    <weixinUrl :visible.sync="weixinUrlVisible" v-if="weixinUrlVisible" :weixinUrlResult="weixinUrlResult" />
  </el-container>
</template>

<script>
import weixin_result from "@/components/weixin_result.vue";
import weixinUrl from "@/components/weixinUrl.vue";

export default {
  components:{
    weixin_result,
    weixinUrl,
  },
  created() {
    this.$api.isShowsynFromWeixin(
      {
        onSucess: resp => {
          
          this.isShow = resp.data.data;
        }
      }
    );
    this.$api.getWechatConfig(
      { domainid: this.$route.query.domainid},
      {
        onSucess: resp => {
          
          this.wechatConfigs = resp.data.data;
          this.changeShow()
          this.onVerifyBtnClick("clickVerifyBtn");
        }
      }
    );
    //关于标题的处理
    this.headerArr={iconfont:'icon-icon_wxpz_off',content:this.$t('weixinConfig'),listHeaderClass:'noListHeader', btnArr:[{type:'primary',name:'save',label:this.$t('save')}] }
  },
  data() {
    return {
      scrollHeight: null,
      wechatConfigs: {},
      weixinResultVisible:false,
      weixinResult:{},
      loading:false,
      isnotEditAgentId:true,
      isEditAgentId:false,
      rules:{
        weixinCorpID:[
          { required: true, message: this.$t('wechat_corporate'), trigger: 'blur'}
        ],
        weixinCorpSecret:[
          {required: true, message: this.$t('wechat_address_book')+'Secret', trigger: 'blur'}
        ],
        serverHost:[
          {required: true, message: this.$t('wechat_access_system'), trigger: 'blur'}
        ],
        
      },
      weixinUrlVisible:false,
      weixinUrlResult:null,
      isShowAdminBtn: false, //是否显示企业微信后台按钮
      mode:"weixin",
      isShow:"true",
      headerArr:{},
    };
  },
  methods: {
    onBack(){
      this.weixinResultVisible=false;
    },
    onBtnClick(name){
      if(name=='save'){this.onSaveBtnClick('wechatConfigs')}
      else if(name=='weixin_admin'){this.onClickWeixinAdmin()}
      else if(name=='synchronize_domain'){this.onSync2Weixin()}
      else if(name=='synchronize_organizational'){this.onSynFromWeixin()}
    },
    changeShow(isShowAdminBtn){
      let temp=[],tempArr=[]
      if(this.wechatConfigs.weixinProxyType=='EnterpriseWeChat'){
        if(isShowAdminBtn){
          tempArr=[
            {
              name:"weixin_admin",label:this.$t('weixin_admin')
            },
            ]
        }else{
          tempArr=[
            {
              name:"synchronize_domain",label:this.$t('synchronize_domain')
            },{
              name:"synchronize_organizational",label:this.$t('synchronize_organizational')
            }]
        }
        temp=[...this.headerArr.btnArr,...tempArr]
      }else{
         temp=[this.headerArr.btnArr.shift()]
      }
      this.$set(this.headerArr,"btnArr",temp)
    },
    //保存按钮
    onSaveBtnClick(formName) {
      for(let k in this.wechatConfigs){
        if(typeof this.wechatConfigs[k]=="string")
        this.wechatConfigs[k]=this.wechatConfigs[k].replace(/^\s*/,"")
      }
      this.$refs[formName].validate((valid) => {
        if (valid||this.wechatConfigs.weixinProxyType=='none') {
          this.$api.updateWechatConfig(
            { domainid: this.$route.query.domainid, data: this.wechatConfigs },
            {
              onSucess: resp => {
                if (resp.data.errcode == 0) {
                  this.$message({
                    showClose: true,
                    message: this.$t('msg_save_success'),
                    type: "success"
                  });
                } else {
                  this.$message({
                    showClose: true,
                    message: resp.data.errmsg,
                    type: "error"
                  });
                }
              }
            }
          );
        } else {
          return false;
        }
      });
    },
    //保存单个的微信应用agentid
    onSaveWeixinAgentId(row){
      this.$api.saveAgentId(
        {
          domainid: this.$route.query.domainid,
          applicationid: row.id,
          id:row.weixinAgentId,
        },
        {
          onSucess: resp => {
            if (resp.data.errcode == 0) {
              this.$message({
                showClose: true,
                message: this.$t('wechat_application')+"agentid"+this.$t('update_success'),
                type: "success"
              });
            } else {
              this.$message({
                showClose: true,
                message: this.$t('wechat_application')+"agentid"+this.$t('update_failed'),
                type: "error"
              });
            }
          }
        }
      );
    },
    //保存单个的微信应用secret
    onSaveWeixinSecret(row){
      this.$api.saveSecret(
        {
          domainid: this.$route.query.domainid,
          applicationid: row.id,
          secret:row.weixinSecret,
        },
        {
          onSucess: resp => {
            if (resp.data.errcode == 0) {
              this.$message({
                showClose: true,
                message: this.$t('wechat_application')+"secret"+this.$t('update_success'),
                type: "success"
              });
            } else {
              this.$message({
                showClose: true,
                message: this.$t('wechat_application')+"secret"+this.$t('update_failed'),
                type: "error"
              });
            }
          }
        }
      );
    },
    //验证连接
    onVerifyBtnClick(message) {
      if(this.wechatConfigs.weixinCorpID == "" || this.wechatConfigs.weixinCorpSecret == ""){
        if(message && message == "clickVerifyBtn") return false;
        this.$message({
          showClose: true,
          message: this.$t('msg_timeout'),
          type: "error"
        });
        return false;
      }
      this.$api.verifyWechatConfig(
        {
          domainid: this.$route.query.domainid,
          corpid: this.wechatConfigs.weixinCorpID,
          corpsecret: this.wechatConfigs.weixinCorpSecret,
        },
        {
          onSucess: resp => {
            if (resp.data.errcode == 0) {
              if(message && message == "clickVerifyBtn"){
                this.isShowAdminBtn = true;
                this.changeShow(this.isShowAdminBtn)
                return false;
              }
              this.$message({
                showClose: true,
                message: this.$t('msg_verified_success'),
                type: "success"
              });
            } else {
              if(message && message == "clickVerifyBtn") return false;
              this.$message({
                showClose: true,
                message: this.$t('msg_verified_failed'),
                type: "error"
              });
            }
          }
        }
      );
    },
    //生成跳转链接
    genWeChatURL(row) {
      if(row.weixinAgentId==""||row.weixinAgentId==null){
        this.$message({
          showClose: true,
          message: this.$t('msg_require_agentId'),
          type: "error"
        });
        return false;
      }else if(row.weixinSecret==""||row.weixinSecret==null){
        this.$message({
          showClose: true,
          message: this.$t('msg_require_secret'),
          type: "error"
        });
        return false;
      }
      this.$api.genWeChatURL(
        {
          domainid: this.$route.query.domainid,
          applicationid: row.id,
        },
        {
          onSucess: resp => {
            if (resp.data.errcode == 0) {
              this.weixinUrlResult=resp.data.data;
              this.weixinUrlVisible=true;
            } else {
              this.$message({
                showClose: true,
                message: resp.data.errmsg,
                type: "error"
              });
            }
          }
        }
      );
    },
    //同步微信到域(租户)
    onSynFromWeixin(){
      this.loading=true;
      this.$api.synFromWeixin(
        {
          domainid: this.$route.query.domainid,
        },
        {
          onSucess: resp => {
            
            if (resp.data.errcode == 0) {
              this.weixinResult={}
              this.weixinResult=resp.data.data;
              this.loading=false;
              this.weixinResultVisible=true;
            } 
          },
          onError:(resp) => {
            this.$message({
              showClose: true,
              message: resp.data.errmsg,
              type: "error"
            });
          }
        }
      );
    },
    onClickWeixinAdmin() {
      let domainid = this.$route.query.domainid;
      let showLdapButton = this.$route.query.showLdapButton;
      let name = this.$route.query.name;
      let url = "#/weixin_admin?domainid=" + domainid + "&showLdapButton=" + showLdapButton + "&name=" + name;
      window.open(url);
    },
    //同步域(租户)到微信
    onSync2Weixin(){
      this.loading=true;
      this.$api.sync2Weixin(
        {
          domainid: this.$route.query.domainid,
        },
        {
          onSucess: resp => {
            if (resp.data.errcode == 0) {
              this.weixinResult={}
              this.weixinResult=resp.data.data;
              this.loading=false;
              this.weixinResultVisible=true;

            } 
            
          },
          onError:(resp) => {
            this.$message({
              showClose: true,
              message: resp.data.errmsg,
              type: "error"
            });
          }
        }
      );
    },
    //编辑单个的微信应用agentid
    editAgentId(row){
      this.$prompt(this.$t('enter_wechat_agentid'), '', {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
      }).then(({ value }) => {
        row.weixinAgentId=value?value:"";
        this.onSaveWeixinAgentId(row,value)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('msg_cancel')
        });       
      });
    },
    editSecret(row){
      this.$prompt(this.$t('enter_wechat_secret'), '', {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
      }).then(({ value }) => {
        row.weixinSecret=value?value:"";
        this.onSaveWeixinSecret(row,value)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('msg_cancel')
        });       
      });
    }
  },
  mounted(){
    this.scrollHeight=(document.documentElement.clientHeight || document.body.clientHeight) - 90
  },
};
</script>

<style>

</style>